package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.LoginMapper;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.properties.SecurityProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 用户登录
     */
    @Override
    public UserVo login(LoginDto loginDto) {
        // 判断用户名和密码是否为空
        if (StrUtil.isEmpty(loginDto.getUsername()) || StrUtil.isEmpty(loginDto.getPassword())) {
            throw new BaseException(BasicEnum.PARAMETER_MISSING);
        }
        // 根据用户名查询用户信息
        User user = loginMapper.queryUserInfoByUsername(loginDto.getUsername());
        // 判断用户是否存在
        if (user == null) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        // 判断用户是否是禁用状态
        if (StrUtil.equals(user.getDataState(), SuperConstant.DATA_STATE_1)) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        // 校验密码是否正确
        boolean checkpw = BCrypt.checkpw(loginDto.getPassword(), user.getPassword());
        if (!checkpw) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        // 判断当前用户有没有关联菜单
        List<Resource> resourceList = loginMapper.queryResourceByUserId(user.getId());
        if (CollectionUtil.isEmpty(resourceList)) {
            throw new BaseException(BasicEnum.NO_MENU);
        }
        // 保存用户的可访问资源列表到Redis中 (url)
        List<String> requestPathList = resourceList.stream().map(Resource::getRequestPath).collect(Collectors.toList());
        requestPathList.addAll(securityProperties.getWhiteList());
        redisTemplate.opsForValue().set(CacheConstants.ACCESS_URLS + user.getId(), JSONUtil.toJsonStr(requestPathList), jwtTokenProperties.getTtl(),TimeUnit.SECONDS);
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        // 脱敏
        userVo.setPassword("");

        // 生成JWT令牌返回
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERINFO, JSONUtil.toJsonStr(userVo));
        String jwt = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(), getOffsetDate(jwtTokenProperties.getTtl()), claims);
        userVo.setUserToken(jwt);
        return userVo;
    }

    private int getOffsetDate(Integer ttl) {
        Long day = Convert.convertTime(ttl, TimeUnit.SECONDS, TimeUnit.DAYS);
        return day.intValue();
    }
}
